var express = require('express');
var sql = require('../sql/index');
var Pro = require('../sql/col/Pro');
var User = require('../sql/col/User');
var Cart = require('../sql/col/Cart');
var router = express.Router();

router.get('/list', (req, res, next) => {
  sql.find(Cart, {}, { _id:0 }).then(data => {
    // 请求到的是所有购物车的数据
    // [{cart_id: '', userid: '', proid: '', num: '', flag: ''}]
    // 循环遍历数据,获取userid对应的用户信息,获取porid对应的产品信息
    const arr = [];
    data.forEach(item => {
      arr.push(sql.find(User, { userid: item.userid }, { _id:0 }))
      arr.push(sql.find(Pro, { proid: item.proid }, { _id:0 }))
    })

    Promise.all(arr).then(result => {
      const list = []
      result.forEach((item, index) => {
        let obj = {}
        if (index % 2 === 0) {
          // 获取用户信息
          obj.userid = result[index][0].userid
          obj.username = result[index][0].username
          obj.tel = result[index][0].tel
          // 获取产品信息
          obj.proid = result[index + 1][0].proid
          obj.proname = result[index + 1][0].proname
          obj.proimg = result[index + 1][0].proimg
          obj.price = result[index + 1][0].price
          // 获取购物车信息 -- 购物车id,数量,选中状态
          obj.cartid = data[Math.floor(index / 2)].cartid
          obj.num = data[Math.floor(index / 2)].num
          obj.flag = data[Math.floor(index / 2)].flag
          list.push(obj)
        }
      })
      res.send({
        code: '200',
        message: '获取购物车的数据',
        data: list
      })
    })
  })
})


module.exports = router;